<?php

namespace App\Service\Admin;

use App\Model\Admin;
use App\Service\BaseService;
use App\Utils\StrHash;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;

class AdminService extends BaseService
{
    /**
     * 获取管理员列表
     * @param array $request
     * @return array
     */
    public function lists(array $request)
    {
        $lists = Admin::query()->with("role")->orderBy("id", "asc");
        if (!isset($request['page']) || empty($request['page'])) {
            $request['page'] = "0";
        }
        if (!isset($request['limit']) || empty($request['limit'])) {
            $request['limit'] = "10";
        }
        if (isset($request['username']) && $request['username'] != '') {
            $lists = $lists->where("username", "like", "%" . $request['username'] . "%");
        }
        if (isset($request['mobile']) && $request['mobile'] != '') {
            $lists = $lists->where("mobile", "like", "%" . $request['mobile'] . "%");
        }
        if (isset($request['status']) && $request['status'] != '') {
            $lists = $lists->where("status", $request['status']);
        }
        $data['count'] = $lists->count();
        $data['lists'] = $lists->skip(($request['page'] - 1) * $request['limit'])->take($request['limit'])->get();
        return $this->baseResponse(0, "获取管理员列表成功", $data);
    }

    /**
     * 创建管理员
     * @param array $request
     * @return array
     */
    public function create(array $request)
    {
        if (Admin::query()->create($request)) {
            return $this->baseResponse(0, "创建管理员成功");
        }
        return $this->baseResponse(1, "创建管理员失败");
    }

    /**
     * 通过Id获取管理员
     * @param int $id 管理员ID
     * @return Builder|Builder[]|Collection|Model|null
     */
    public function get(int $id)
    {
        return $this->baseResponse(0, "获取管理员成功", Admin::query()->find($id));
    }

    /**
     * 通过Id编辑管理员
     * @param int $id 管理员ID
     * @param array $request
     * @return array
     */
    public function update(int $id, array $request)
    {
        if (isset($request['password']) && $request['password'] != '') {
            $request['password'] = StrHash::hash($request['password']);
        } else {
            unset($request['password']);
        }
        if (Admin::query()->find($id)->update($request)) {
            return $this->baseResponse(0, "管理员修改成功");
        }
        return $this->baseResponse(1, "管理员修改失败");
    }

    /**
     * 通过Id删除管理员
     * @param int $id
     * @return array
     */
    public function delete(int $id)
    {
        if ($id == 1) return $this->baseResponse(1, "系统管理员无法删除！");
        if (Admin::destroy($id)) {
            return $this->baseResponse(0, "删除管理员成功");
        }
        return $this->baseResponse(1, "删除管理员失败");
    }
}